#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys,os,re
import urllib,urllib2,urlparse
from wwpy.util.Logger import logger

class Url(object):
    
    def __init__(self,url):
        self.url=url
        
    def set(self,url):
        self.url=url
        
    def get(self):
        return self.url
        
    def request(self,params=None,headers={},file=None):
        data=None
        if params is not None:
            data=urllib.urlencode(params)
        req=urllib2.Request(self.url,data,headers=headers)
        if data is not None:
            self.set(''.join([self.url,req.data]))
        try:
            r=urllib2.urlopen(req)
            data=r.read()
            r.close()
            if file is not None:
                logger.info('Get data from %s into file %s.' % (self.url,file))
                with open(file,'wb') as f:
                    f.write(data)
            else:
                return data
        except urllib2.URLError,e:
            return str(e.reason)
            
    def download(self,file=None,grep=None,line_func=None):
        try:
            r=urllib2.urlopen(self.url)
            if file is None:
                info=r.info()
                if 'Content-Disposition' in info:
                    file=info['Content-Disposition'].split('filename=')[1]
                    if file.startswith("'") or file.startswith('"'):
                        file=file[1:-1]
                    if r.url.find('/')>-1:
                        file=os.path.basename(urlparse.urlsplit(r.url)[2])
            logger.info('Download from %s into file %s.' % (self.url,file))
            if grep is not None:
                regex=re.compile(grep)
            with open(file,'wb') as f:
                for line in r:
                    if grep is not None:
                        matched=regex.search(line)
                        if not matched:
                            continue
                    if line_func is not None:
                        line=line_func(line)
                        if line is not None:
                            f.write(line)
                    else:
                        f.write(line)
        except urllib2.URLError,e:
            print str(e.reason)
            
    @classmethod
    def send(cls,msg,mobiles=None):
        if mobiles is None:
            mobiles='13401145805'
        if isinstance(mobiles,(tuple,list)):
            mobiles=','.join(str(mobile) for mobile in mobiles)
        elif isinstance(mobiles,dict):
            mobiles=','.join(str(mobile) for mobile in mobiles.values())
        else:
            mobiles=mobiles
        msg=str(msg).decode('utf8').encode('gbk')
        url="http://221.179.180.158:9002/QxtSms/QxtFirewall?"
        obj=cls(url)
        params=dict(OperID='58tc4',OperPass=123456,SendTime='',ValidTime='',AppendID='',DesMobile=mobiles,Content=msg,ContentType=8)
        return obj.request(params)
    
if __name__ == '__main__':
    url=Url('http://10.5.12.167:50075/streamFile/dsap/rawdata/jzcpclog/20130505/jingzhun_clicks_2013050500')
    url.download()
    Url.send('this is a test msg.')
    
